package com.b2c.erp.controller.bigData;

import com.alibaba.fastjson.JSONObject;
import com.b2c.entity.api.ApiResult;
import com.b2c.entity.DataRow;
import com.b2c.entity.KeyWordEntity;
import com.b2c.entity.result.EnumResultVo;
import com.b2c.interfaces.ecom.KeyWordService;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.yaml.snakeyaml.util.UriEncoder;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;

@RequestMapping("/big_data")
@Controller
public class KeyWordController {
    @Autowired
    private KeyWordService keyWordService;
    private static Logger log = LoggerFactory.getLogger(KeyWordController.class);
    /**
     * 订单列表
     *
     * @param model
     * @param request
     * @return
     */
    @RequestMapping(value = "/keyword_list", method = RequestMethod.GET)
    public String list(Model model, HttpServletRequest request) {
        String page = request.getParameter("page");
        Integer pageIndex = 1;
        Integer pageSize = 100;
        String year = "";
        String source = "";
        Integer categoryId = null;

        String keyword = "";

        if (!StringUtils.isEmpty(page)) {
            pageIndex = Integer.parseInt(page);
        }

        if (!StringUtils.isEmpty(request.getParameter("keyword"))) {
            keyword = request.getParameter("keyword");
            model.addAttribute("keyword",keyword);
        }
        if (!StringUtils.isEmpty(request.getParameter("year"))) {
            year = request.getParameter("year");
            model.addAttribute("year",year);
        }

        if (!StringUtils.isEmpty(request.getParameter("source"))) {
            source = request.getParameter("source");
            model.addAttribute("source", source);
        }
        if (!StringUtils.isEmpty(request.getParameter("category"))) {
            model.addAttribute("category", request.getParameter("category"));
        }
        
        if (!StringUtils.isEmpty(request.getParameter("categoryId"))) {
            categoryId = Integer.parseInt(request.getParameter("categoryId"));
            model.addAttribute("categoryId", categoryId);
        }
        Long parentId = null;
        if (!StringUtils.isEmpty(request.getParameter("parentId"))) {
            parentId = Long.parseLong(request.getParameter("parentId"));
            model.addAttribute("parentId", parentId);
        }
        if(parentId!=null && parentId > 0){
            var m = keyWordService.getById(parentId);
            model.addAttribute("parentName",m.getKeyword());
        }

        var result = keyWordService.getList(pageIndex,pageSize,source,year,keyword,parentId,categoryId);
        model.addAttribute("pageIndex", pageIndex);
        model.addAttribute("pageSize", pageSize);
        model.addAttribute("totalSize", result.getTotalSize());
        model.addAttribute("lists", result.getList());

        model.addAttribute("view", "keyword");
        model.addAttribute("pView", "sale");
        return "bigData/keyword_list";
    }


    @RequestMapping(value = "/keyword_add", method = RequestMethod.GET)
    public String add(Model model, HttpServletRequest request) {
        return "bigData/keyword_add";
    }

    @ResponseBody
    @RequestMapping(value = "/keyword_add_ajax", method = RequestMethod.POST)
    public  ApiResult<String> addPostAjax(Model model, @RequestBody DataRow data, HttpServletRequest request) {
        KeyWordEntity kw = new KeyWordEntity();
        kw.setCategory(data.getString("category"));
        kw.setParentId(data.getLong("parent1"));
        kw.setKeyword( data.getString("keyword"));
        kw.setSousuorenqi(data.getInt("sousuorenqi"));
        kw.setDianjirenqi(data.getInt("dianjirenqi"));
        kw.setDianjilv(data.getBigDecimal("dianjilv"));
        kw.setZhifulv(data.getBigDecimal("zhifulv"));
        kw.setIncludeDate(data.getString("include_date"));

        keyWordService.addKeyWord(kw);
        return new ApiResult<>(EnumResultVo.SUCCESS.getIndex(), "SUCCESS");
    }


    @RequestMapping(value = "/keyword_import", method = RequestMethod.GET)
    public String excelImport(Model model, HttpServletRequest request) {
        var parentList = keyWordService.getParentList(0l);
        model.addAttribute("parentList",parentList);
        String msg = request.getParameter("msg");
        model.addAttribute("msg",msg);
        model.addAttribute("view", "keyword");
        model.addAttribute("pView", "goods");
        return "bigData/keyword_import";
    }

    @RequestMapping(value = "/keyword_import", method = RequestMethod.POST)
    public String excelImportPOST(Model model, @RequestParam("excel") MultipartFile file, HttpServletRequest request) throws IOException {
        String fileName = file.getOriginalFilename();
        if(StringUtils.isEmpty(fileName)){
            log.error("没有选择文件");
            return "redirect:/big_data/keyword_import?msg="+ UriEncoder.encode("没有选择文件");
        }else if(fileName.substring(fileName.indexOf(".")+1,fileName.length()).toLowerCase().equals("xlsx")==false){
            log.error("文件不是xlsx文件");
            return "redirect:/big_data/keyword_import?msg="+ UriEncoder.encode("文件不是xlsx文件");
        }

        String category = request.getParameter("category");
        Long parent1 = 0l;
        Long parent2 = 0l;
        if(StringUtils.hasText(request.getParameter("parent1"))){
            parent1 = Long.parseLong(request.getParameter("parent1"));
        }
        if(StringUtils.hasText(request.getParameter("parent2"))){
            parent2 = Long.parseLong(request.getParameter("parent2"));
        }
        String include_date = request.getParameter("include_date");

        String dir = System.getProperty("user.dir");
        String destFileName = dir + File.separator + "uploadedfiles_" + fileName;
//        System.out.println(destFileName);
        File destFile = new File(destFileName);
        file.transferTo(destFile);
        log.info("/***********关键词数据导入，文件后缀" + destFileName.substring(destFileName.lastIndexOf(".")) + "***********/");

        XSSFSheet sheet;
        InputStream fis = null;

        fis = new FileInputStream(destFileName);

        //数据list
        int successCount = 0;

        XSSFWorkbook workbook = null;
        try {
            workbook = new XSSFWorkbook(fis);
            log.info("/***********关键词数据导入***读取excel文件成功***********/");

            sheet = workbook.getSheetAt(0);

            int lastRowNum = sheet.getLastRowNum();//最后一行索引


            //循环读取excel数据
            for (int i = 1; i <= lastRowNum; i++) {
                XSSFRow row  = sheet.getRow(i);
                KeyWordEntity vo = new KeyWordEntity();
                vo.setKeyword(row.getCell(0).getStringCellValue());
                if(parent2 > 0) {
                    try {
                        vo.setSousuorenqi(Integer.parseInt(row.getCell(1).getStringCellValue()));
                    } catch (Exception e1) {
                        vo.setSousuorenqi((int) row.getCell(1).getNumericCellValue());
                    }
                    try {
                        vo.setSousuoredu(Integer.parseInt(row.getCell(2).getStringCellValue()));
                    } catch (Exception e1) {
                        vo.setSousuoredu((int) row.getCell(2).getNumericCellValue());
                    }
                    try {
                        vo.setDianjilv(new BigDecimal(row.getCell(3).getStringCellValue()));
                    } catch (Exception e3) {
                        vo.setDianjilv(new BigDecimal(row.getCell(3).getNumericCellValue()));
                    }
                    try {
                        vo.setDianjirenqi(Integer.parseInt(row.getCell(4).getStringCellValue()));
                    } catch (Exception e2) {
                        vo.setDianjirenqi((int) row.getCell(4).getNumericCellValue());
                    }
                    try {
                        vo.setDianjiredu(Integer.parseInt(row.getCell(5).getStringCellValue()));
                    } catch (Exception e2) {
                        vo.setDianjiredu((int) row.getCell(5).getNumericCellValue());
                    }
                    vo.setZhifulv(new BigDecimal(0.0));
                    vo.setDepth(3);
                }else{
                    try {
                        vo.setSousuorenqi(Integer.parseInt(row.getCell(2).getStringCellValue()));
                    } catch (Exception e1) {
                        vo.setSousuorenqi((int) row.getCell(2).getNumericCellValue());
                    }
                    try {
                        vo.setDianjirenqi(Integer.parseInt(row.getCell(3).getStringCellValue()));
                    } catch (Exception e2) {
                        vo.setDianjirenqi((int) row.getCell(3).getNumericCellValue());
                    }
                    try {
                        vo.setDianjilv(new BigDecimal(row.getCell(4).getStringCellValue()));
                    } catch (Exception e3) {
                        vo.setDianjilv(new BigDecimal(row.getCell(4).getNumericCellValue()));
                    }
                    try {
                        vo.setZhifulv(new BigDecimal(row.getCell(5).getStringCellValue()));
                    } catch (Exception e4) {
                        vo.setZhifulv(new BigDecimal(row.getCell(5).getNumericCellValue()));
                    }
                    vo.setDepth(2);
                    vo.setSousuoredu(0);
                    vo.setDianjiredu(0);
                }
                vo.setCategory(category);
                vo.setIncludeDate(include_date);
                vo.setParentId(parent2 >0 ? parent2 : parent1);

                log.info("/***********关键词数据导入***读取excel文件"+i+"行："+ JSONObject.toJSONString(vo) +"***********/");
                keyWordService.addKeyWord(vo);
                successCount++;
            }


        }catch (Exception e){
            log.info("/***********数据导入***出现异常：" + e.getMessage() + "***********/");
            return "redirect:/big_data/keyword_import?msg="+ UriEncoder.encode(e.getMessage());
        }

        model.addAttribute("view", "keyword");
        model.addAttribute("pView", "data");
        return "redirect:/big_data/keyword_list?parentId="+(parent2 >0 ? parent2 : parent1);
    }
}
